// app.js
import config from './utils/config'
import { request } from './utils/request'
App({
    onLaunch(e) {
        var query = e.query
        if('extension' in query){
            var extension = query.extension
        }else{
            var extension = ''
        }
        this.login(extension)
        this.updateApp()
        // wx.loadFontFace({
        //   family: 'milan',
        //   global:true,
        //   source: 'url("'+config.url+'/system/api/downFont?font=xmltpro.ttf")',
        //   success:(res)=>{
        //     console.log(res)
        //   },
        //   fail:err=>{
        //     console.log(err)
        //   }
        // })
    },
    globalData: {
        userInfo: null,
        custom: null
    },
    updateApp(extension='') {
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        updateManager.applyUpdate()
                    }
                }
            })
        })
    },
    login(extension) {
        var userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
            wx.login({
                success: res => {
                    request({
                        url: '/miniprogram/system/login',
                        type: 'get',
                        data: { code: res.code,extension }
                    }).then(res => {
                        if (res.code == 200) {
                            wx.setStorageSync('userInfo', res.data)
                            this.globalData.userInfo = res.data
                        } else {
                            wx.showToast({
                                title: '登录失败',
                                icon: 'none'
                            })
                        }
                    })
                }
            })
        } else {
            request({
                url: '/miniprogram/system/getInfo',
                data: { id: userInfo.id }
            }).then(res => {
                wx.setStorageSync('userInfo', res.data)
                this.globalData.userInfo = res.data
            })
        }
    },
    getInfo(user_id){
        request({
            url: '/miniprogram/system/getInfo',
            data: { id: user_id }
        }).then(res => {
            wx.clearStorageSync()
            wx.setStorageSync('userInfo', res.data)
            this.globalData.userInfo = res.data
        })
    }
})
